package com.videoweb.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.videoweb.entity.Menu;
import com.videoweb.entity.Role;
import com.videoweb.entity.User;
import com.videoweb.service.IMenuService;
import com.videoweb.service.IRoleService;
import com.videoweb.utils.AjaxResult;
import com.videoweb.utils.SecurityUtils;
import com.videoweb.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  角色管理前端控制器
 * </p>
 *
 * @author lmr
 * @since 2025-05-17
 */
@RestController
@RequestMapping("/system/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    /**
     * 获取角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public AjaxResult list(Role role) {
        List<Role> list = roleService.selectRoleList(role);
        return AjaxResult.success(list);
    }

    /**
     * 分页获取角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          Role role) {
        Page<Role> page = new Page<>(pageNum, pageSize);
        IPage<Role> list = roleService.selectRolePage(page, role);
        return AjaxResult.success(list);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        Role role = roleService.selectRoleById(roleId);
        return AjaxResult.success(role);
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Role role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return AjaxResult.error("新增角色'" + role.getName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return AjaxResult.error("新增角色'" + role.getName() + "'失败，角色权限已存在");
        }
        role.setCreatedAt(java.time.LocalDateTime.now());
        role.setUpdatedAt(java.time.LocalDateTime.now());
        if (roleService.insertRole(role)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("新增角色失败");
    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Role role) {
        roleService.checkRoleAllowed(role);
        if (!roleService.checkRoleNameUnique(role)) {
            return AjaxResult.error("修改角色'" + role.getName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return AjaxResult.error("修改角色'" + role.getName() + "'失败，角色权限已存在");
        }
        role.setUpdatedAt(java.time.LocalDateTime.now());
        if (roleService.updateRole(role)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色失败");
    }

    /**
     * 角色状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Role role) {
        roleService.checkRoleAllowed(role);
        role.setUpdatedAt(java.time.LocalDateTime.now());
        if (roleService.updateRoleStatus(role)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色状态失败");
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        if (roleService.deleteRoleByIds(roleIds)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("删除角色失败");
    }

    /**
     * 获取角色选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<Role> roles = roleService.selectRoleAll();
        return AjaxResult.success(roles);
    }

    /**
     * 查询已分配角色用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/authUser/allocatedList")
    public AjaxResult allocatedList(User user) {
        // 这里需要实现查询已分配角色的用户列表
        // 暂时返回空列表
        return AjaxResult.success();
    }

    /**
     * 查询未分配角色用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/authUser/unallocatedList")
    public AjaxResult unallocatedList(User user) {
        // 这里需要实现查询未分配角色的用户列表
        // 暂时返回空列表
        return AjaxResult.success();
    }
//
//    /**
//     * 取消用户授权角色
//     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
//    @PutMapping("/authUser/cancel")
//    public AjaxResult cancelAuthUserAll(@RequestBody Map<String, Object> params) {
//        // 这里需要实现取消用户授权角色
//        return AjaxResult.success();
//    }
//
//    /**
//     * 批量取消用户授权角色
//     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
//    @PutMapping("/authUser/cancelAll")
//    public AjaxResult cancelAuthUserAll(@RequestBody Map<String, Object> params) {
//        // 这里需要实现批量取消用户授权角色
//        return AjaxResult.success();
//    }

    /**
     * 授权用户选择
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(@RequestBody Map<String, Object> params) {
        // 这里需要实现授权用户选择
        return AjaxResult.success();
    }

    /**
     * 获取对应角色部门树列表
     */
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId) {
        // 这里需要实现获取对应角色部门树列表
        // 暂时返回空列表
        return AjaxResult.success();
    }

    /**
     * 数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody Role role) {
        roleService.checkRoleAllowed(role);
        if (roleService.authDataScope(role)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改数据权限失败");
    }

    /**
     * 获取角色已分配菜单ID列表
     */
    @GetMapping("/menu/{roleId}")
    public AjaxResult getRoleMenu(@PathVariable Long roleId) {
        List<Long> menuIds = menuService.selectMenuIdsByRoleId(roleId);
        return AjaxResult.success(menuIds);
    }

    /**
     * 保存角色菜单权限
     */
    @PutMapping("/menu")
    public AjaxResult updateRoleMenu(@RequestBody Map<String, Object> params) {
        Long roleId = Long.valueOf(params.get("roleId").toString());
        List<Integer> menuIds = (List<Integer>) params.get("menuIds");
        menuService.updateRoleMenus(roleId, menuIds);
        return AjaxResult.success();
    }
}
